#ifndef TARGET_H
#define TARGET_H

#include <QtCore>
#include <QtNetwork>

enum tgtFuncCode
{
    tfcParmReadHardware=0x00,
    tfcParmReadDevice=0x01,
    tfcParmReadHy103=0x02,
    tfcParmReadDevProtocol=0x03,

    tfcParmWriteHardware=0x10,
    tfcParmWriteDevice=0x11,
    tfcParmWriteHy103=0x12,
    tfcParmWriteDevProtocol=0x13,

    tfcMonHy103Eth0=0x20,
    tfcMonHy103Eth1=0x21,

    tfcMonHy103BasicInfoEth0=0x22,
    tfcMonHy103UdpEth0=0x23,
    tfcMonHy103TcpSendEth0=0x24,
    tfcMonHy103TcpRecvEth0=0x25,

    tfcMonHy103BasicInfoEth1=0x28,
    tfcMonHy103UdpEth1=0x29,
    tfcMonHy103TcpSendEth1=0x2A,
    tfcMonHy103TcpRecvEth1=0x2B,

    tfcMonCan0=0x30,

    tfcMonCan0BasicInfo=0x31,
    tfcMonCan0Send=0x32,
    tfcMonCan0Recv=0x33,

    tfcMonCan1=0x40,

    tfcMonCan1BasicInfo=0x41,
    tfcMonCan1Send=0x42,
    tfcMonCan1Recv=0x43,

    tfcSectorList=0xF0,
    tfcChangeSector=0xF1,
    tfcBasicStatus=0xFE,
    tfcConfirm=0xFF
};

enum PVType
{
    pvAi=1,
    pvDi=2,
    pvPi=3,
    pvDo=4,
    pvAction=5,
    pvAlarm=6
};

enum EventType
{
    etAction=2,
    etAlarm=3
};

class TargetManager : public QThread
{
    Q_OBJECT
public:
    TargetManager(const QString& ip,quint16 port,const QString& filePath,QObject *parent = 0);
    ~TargetManager();

public:
    bool doCommand(tgtFuncCode funcCode,const QByteArray& data=QByteArray());
    void setFilePath(const QString& filePath){m_filePath=filePath;}

signals:
    void sigConnectStatus(bool status);
    void sigCommand(QByteArray data);
    void monitorData(QByteArray data);

protected:
    virtual void run();

protected slots:
    void processDisconnect();
    void processData(QByteArray data);

private:
    QString m_ip;
    quint16 m_port;
    QString m_filePath;

    bool m_bcommandStatus;

    QWaitCondition m_wait;
    QMutex m_mutex;
};

#define MAX_FRAME_LEN 1010

class Target : public QObject
{
    Q_OBJECT
public:
    Target(const QString& ip,quint16 port,QObject *parent = 0);
    ~Target();

signals:
    void sigDisconnect();
    void sigData(QByteArray data);

protected slots:
    void processRecv();
    void processDisconnect();
    void sendCmd(QByteArray data);

public:
    void init();
    bool isConnected(){return m_bconnect;}


private:
    QTcpSocket* m_server;

    QString m_ip;
    quint16 m_port;

    quint8 m_recvBuf[16];
    quint16 m_frameLen;
    QByteArray m_data;

    bool m_bconnect;
};

#endif // TARGET_H
